<template>
  <div class="shop-pagination">
    <a @click="changePager(currentPage-1)" v-if="currentPage>1" href="javascript:;">上一页</a>
    <a v-else href="javascript:;" class="disabled">上一页</a>
    <span v-if="pager.start>1">...</span>
    <a @click="changePager(i)" href="javascript:;" v-for="i in pager.btnArr" :key="i" :class="{active:i===currentPage}">{{i}}</a>
    <span v-if="pager.end<pager.totalPage">...</span>
    <a @click="changePager(currentPage+1)" v-if="currentPage<pager.totalPage" href="javascript:;">下一页</a>
    <a v-else href="javascript:;" class="disabled">下一页</a>
  </div>
</template>
<script>
import { computed, ref, watch } from 'vue'
export default {
  name: 'ShopPagination',
  props: {
    total: {
      type: Number,
      default: 100
    },
    pageSize: {
      type: Number,
      default: 10
    },
    current: {
      type: Number,
      default: 1
    }
  },
  setup(props, { emit }) {
    // 1.约定按钮的个数为5个
    const buttonNum = 5
    // 2.当前显示的页码
    const currentPage = ref(1)
    // 总页数 = 总条数 / 每一页条数 向上取整
    // 3.总条数
    const total = ref(100)
    // 4.每一页的条数
    const pageSize = ref(10)
    // 其他数据依赖以上数据(起始的按钮，结束的按钮，按钮数组)
    const pager = computed(() => {
      // 总页数
      const totalPage = Math.ceil(total.value / pageSize.value)
      // 起始按钮 结束按钮
      // 1.理想
      const offset = Math.floor(buttonNum / 2)
      let start = currentPage.value - offset
      let end = start + buttonNum - 1
      // 2.如果起始页码 <1
      if (start < 1) {
        start = 1
        end = (start + buttonNum - 1) > totalPage ? totalPage : (start + buttonNum - 1)
      }
      // 3.如果结束页码 > 总页码
      if (end > totalPage) {
        end = totalPage
        start = (end - buttonNum + 1) < 1 ? 1 : (end - buttonNum + 1)
      }
      // 得到页码数组
      const btnArr = []
      for (let i = start; i <= end; i++) {
        btnArr.push(i)
      }
      // console.log(btnArr);
      return { totalPage, start, end, btnArr }
    })
    // 监听props的变化，更新组件内部数据
    watch(props, () => {
      total.value = props.total
      pageSize.value = props.pageSize
      currentPage.value = props.current
    }, { immediate: true })
    // 切换页码时触发的函数
    const changePager = (page) => {
      currentPage.value = page
      // 通知父组件
      emit('currentPageChange', page)
    }
    return { currentPage, pager, changePager }
  }
}
</script>
<style scoped lang="less">
.shop-pagination {
  display: flex;
  justify-content: center;
  padding: 30px;
  > a {
    display: inline-block;
    padding: 5px 10px;
    border: 1px solid #e4e4e4;
    border-radius: 4px;
    margin-right: 10px;
    &:hover {
      color: @themeColor;
    }
    &.active {
      background: @themeColor;
      color: #fff;
      border-color: @themeColor;
    }
    &.disabled {
      cursor: not-allowed;
      opacity: 0.4;
      &:hover {
        color: #333
      }
    }
  }
  > span {
    margin-right: 10px;
  }
}
</style>
